package service

import (
	"errors"
	"math"
	"strconv"
	"strings"
	"time"

	"../model"
	"../util"
)

//添加文章
func WritePost(title, content, tagStr string, pubdate int64, catId int64, status int32, postId int64) error {
	//判断catId是否存在
	exists := model.CheckCatExistsById(catId)
	if !exists {
		return errors.New("不存在该栏目分类")
	}
	//根据tag取tagid
	tagsArr := strings.Split(tagStr, ",")
	var tagIdArr []string
	var err error
	for _, tag := range tagsArr {
		id, err := model.GetTagIdByNameAlways(tag)
		if err != nil {
			return err
		}
		tagIdArr = append(tagIdArr, strconv.FormatInt(id, 10))

		//更新 丢弃
		//model.UpdateTagCountById(id)
	}
	tagIdStr := strings.Join(tagIdArr, ",")

	//添加文章
	post := model.NewPost(title, content, catId, pubdate, tagIdStr, 0, status, time.Now().Unix(), 1)
	if postId != 0 {
		post.Id = postId
		_, err = post.UpdatePost()
	} else {
		err = post.InsertPost()
	}
	if err != nil {
		return err
	}
	return nil
}

//获取文章详情
func GetPostDetail(id int64) (map[string]interface{}, error) {
	data := make(map[string]interface{})
	post, err := model.GetPostById(id)
	if err != nil {
		return nil, err
	}
	data["post"] = post
	//获取tags category 信息
	category, err := model.GetCategoryById(post.CatId)
	if err != nil {
		return nil, err
	}
	data["category"] = category
	tags := post.Tags
	tagsArr := strings.Split(tags, ",")
	tagsSlice := []model.Tags{}
	for _, tagNumStr := range tagsArr {
		tagNum, err := util.StringToInt64(tagNumStr)
		if err != nil {
			continue
		}
		tagsObj, err := model.GetTagById(tagNum)
		if err != nil {
			continue
		}
		tagsSlice = append(tagsSlice, tagsObj)
	}
	data["tags"] = tagsSlice
	return data, nil
}

//获取文章列表
func GetPostList(query map[string]interface{}, offset, limit int64) ([]map[string]interface{}, error) {
	data := []map[string]interface{}{}
	posts, err := model.GetPostList(query, limit, offset)
	if err != nil {
		return nil, err
	}
	//fmt.Println(posts, err)

	//整合文章相关数据
	for _, post := range posts {
		item := make(map[string]interface{})
		//根据catId获取category
		category, err := model.GetCategoryById(post.CatId)
		if err != nil {
			return nil, err
		}
		item["post"] = post
		item["category"] = category

		//tags是逗号分隔的字符串
		tags := post.Tags
		tagsArr := strings.Split(tags, ",")
		tagsSlice := []model.Tags{}
		for _, tagNumStr := range tagsArr {
			tagNum, err := util.StringToInt64(tagNumStr)
			if err != nil {
				continue
			}
			tagsObj, err := model.GetTagById(tagNum)
			if err != nil {
				continue
			}
			tagsSlice = append(tagsSlice, tagsObj)
		}
		item["tags"] = tagsSlice
		data = append(data, item)
	}
	return data, nil
}

//获取总页数
func GetPostPageSize(query map[string]interface{}, limit int64) (int64, error) {
	count, err := model.GetPostCount(query)
	if err != nil {
		return 0, err
	}

	countFloat := float64(count)
	limitFloat := float64(limit)
	pageSize := math.Ceil(countFloat / limitFloat)
	return int64(pageSize), nil
}
